package com.example.gcmtest1;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;

public class GCMIntentService extends GCMBaseIntentService {

	private String logName = "GCMIntentService";
	
	public GCMIntentService() {
		
	}
	
	@Override
	protected void onError(Context arg0, String arg1) {
		// TODO Auto-generated method stub
		Log.d(logName, "onError.." + arg1);
	}

	@Override
	protected void onMessage(Context arg0, Intent arg1) {
		// TODO Auto-generated method stub
		Log.d(logName, "onMessage..");
		String key1 = arg1.getExtras().getString("key1");
		Log.d(logName, "key1=" + key1);
		
		NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationCompat.Builder n = new NotificationCompat.Builder(this);
		n.setContentTitle("New Message");
		n.setContentText(key1);
		n.setSmallIcon(R.drawable.ic_launcher);
		
		Intent ii = new Intent(this, MainActivity.class);
		ii.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent i = PendingIntent.getActivity(this, 0, ii, 0);
		
		n.setContentIntent(i);
		
		Notification nn = n.build();   
		
		nm.notify(0, nn);
		Log.d(logName, "should be notified");
		
		/*
		Intent intent = new Intent();
		String CUSTOM_INTENT = "com.example.gcmtest1.intent.action.message.TEST";
		intent.setAction(CUSTOM_INTENT);
		
		Intent i2 = new Intent(this, MainActivity.class);
		i2.setAction(Intent.ACTION_MAIN);
		i2.addCategory(Intent.CATEGORY_LAUNCHER);
		i2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		arg0.startActivity(i2);
		*/
		
		
		
		Log.d(logName, "onMessage done");
		
	}

	@Override
	protected void onRegistered(Context arg0, String arg1) {
		
		Log.d(logName, "onRegistered.." + arg1);
		
		Intent intent = new Intent();
		String CUSTOM_INTENT = "com.example.gcmtest1.intent.action.register.TEST";
		intent.setAction(CUSTOM_INTENT);
		intent.putExtra("regId", arg1);
		
		arg0.sendBroadcast(intent);
		Log.d(logName, "good!!");
		
	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) {
		// TODO Auto-generated method stub
		Log.d(logName, "onUnregistered.." + arg1);
		
	}

}
